package com.jzo2o.foundations.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.expcetions.ForbiddenOperationException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.foundations.enums.FoundationStatusEnum;
import com.jzo2o.foundations.mapper.RegionMapper;
import com.jzo2o.foundations.mapper.ServeItemMapper;
import com.jzo2o.foundations.mapper.ServeMapper;
import com.jzo2o.foundations.model.domain.Region;
import com.jzo2o.foundations.model.domain.Serve;
import com.jzo2o.foundations.model.domain.ServeItem;
import com.jzo2o.foundations.model.dto.request.ServePageQueryReqDTO;
import com.jzo2o.foundations.model.dto.request.ServeUpsertReqDTO;
import com.jzo2o.foundations.model.dto.response.ServeResDTO;
import com.jzo2o.foundations.service.IServeService;
import com.jzo2o.mysql.utils.PageHelperUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@Service
public class ServeServiceImpl extends ServiceImpl<ServeMapper, Serve> implements IServeService {

    @Resource
    private ServeItemMapper serveItemMapper;

    @Resource
    private RegionMapper regionMapper;

    /***
     * 区域服务上架
     * @param id
     */
    @Override
    public void onSale(Long id) {
        //1、查询当前区域服务【草稿或者已下架，才可以上架】
        Serve serve = baseMapper.selectById(id);
        if(serve.getSaleStatus()==FoundationStatusEnum.ENABLE.getStatus()){
            throw new CommonException("当前服务已经启用了， 不能重复启用");
        }

        //2、当前上架的服务必须是已启用
        ServeItem serveItem = serveItemMapper.selectById(serve.getServeItemId());
        if(serveItem.getActiveStatus()!=FoundationStatusEnum.ENABLE.getStatus()){
            throw new CommonException("当前服务未启用！");
        }

        //3、执行上架
        lambdaUpdate().eq(Serve::getId,id).set(Serve::getSaleStatus,FoundationStatusEnum.ENABLE.getStatus()).update();
    }

    /**
     * 删除服务
     *
     * @param id 服务id
     */
    @Override
    @Transactional
    public void deleteById(Long id) {
        Serve serve = baseMapper.selectById(id);
        if(ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //草稿状态方可删除
        if (!(serve.getSaleStatus()==FoundationStatusEnum.INIT.getStatus())) {
            throw new ForbiddenOperationException("草稿状态方可删除");
        }

        //删除服务
        baseMapper.deleteById(id);
    }

    @Override
    @Transactional
    public Serve offSale(Long id){
        Serve serve = baseMapper.selectById(id);
        if(ObjectUtil.isNull(serve)){
            throw new ForbiddenOperationException("区域服务不存在");
        }
        //上架状态
        Integer saleStatus = serve.getSaleStatus();
        //上架状态方可下架
        if (!(saleStatus==FoundationStatusEnum.ENABLE.getStatus())) {
            throw new ForbiddenOperationException("上架状态方可下架");
        }
        //更新下架状态
        LambdaUpdateWrapper<Serve> updateWrapper = Wrappers.<Serve>lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getSaleStatus, FoundationStatusEnum.DISABLE.getStatus());
        update(updateWrapper);
        return baseMapper.selectById(id);
    }

    /**
     * 服务设置热门/取消
     *
     * @param id   服务id
     * @param flag 是否为热门，0：非热门，1：热门
     */
    @Override
    public void changeHotStatus(Long id, int flag) {
        //1.设置热门
        LambdaUpdateWrapper<Serve> updateWrapper = Wrappers.<Serve>lambdaUpdate()
                .eq(Serve::getId, id)
                .set(Serve::getIsHot, flag)
                .set(Serve::getHotTimeStamp, System.currentTimeMillis());
        super.update(updateWrapper);
    }


    /**
     * 根据区域id和售卖状态查询关联服务数量
     * @param regionId   区域id
     * @param saleStatus 售卖状态，0：草稿，1下架，2上架。可传null，即查询所有状态
     * @return 服务数量
     */
    @Override
    public int queryServeCountByRegionIdAndSaleStatus(Long regionId, int saleStatus) {
        LambdaQueryWrapper<Serve> queryWrapper = Wrappers.<Serve>lambdaQuery()
                .eq(Serve::getRegionId, regionId)
                .eq(ObjectUtil.isNotEmpty(saleStatus), Serve::getSaleStatus, saleStatus);
        return baseMapper.selectCount(queryWrapper);
    }

    /**
     * 根据服务项id和售卖状态查询关联服务数量
     * @param  serveItemId  服务项id
     * @param saleStatus 售卖状态，0：草稿，1下架，2上架。可传null，即查询所有状态
     * @return 服务数量
     */
    @Override
    public int queryServeCountByServeItemIdAndSaleStatus(Long serveItemId, int saleStatus) {
        LambdaQueryWrapper<Serve> queryWrapper = Wrappers.<Serve>lambdaQuery()
                .eq(Serve::getServeItemId, serveItemId)
                .eq(ObjectUtil.isNotEmpty(saleStatus), Serve::getSaleStatus, saleStatus);
        return baseMapper.selectCount(queryWrapper);
    }


    /***
     * 修改价格
     * @param id
     * @param price
     */
    @Override
    public void updatePrice(Long id, BigDecimal price) {
        lambdaUpdate().eq(Serve::getId,id).set(Serve::getPrice,price).update();
    }

    /**
     * 批量增加区域的服务数据
     * @param serveUpsertReqDTOList
     */
    @Override
    public void batchAdd(List<ServeUpsertReqDTO> serveUpsertReqDTOList) {
        //1、循环serveUpsertReqDTOList
        serveUpsertReqDTOList.forEach(srt->{
            //2、数据检查
            //2.1 检查当前服务是否存在，如果存在，是否已开启
            ServeItem serveItem = serveItemMapper.selectById(srt.getServeItemId());
            if(ObjectUtil.isEmpty(serveItem)){
                throw new CommonException("当前服务不存在！");
            }

            if(serveItem.getActiveStatus()!= FoundationStatusEnum.ENABLE.getStatus()){
                throw new CommonException("当前服务不可用！");
            }

            //2.2 检查当前区域是否已经添加过该服务
            Integer count = lambdaQuery()
                    .eq(Serve::getRegionId, srt.getRegionId())
                    .eq(Serve::getServeItemId, srt.getServeItemId())
                    .count();

            if(count>0){
                throw new CommonException("当前服务重复添加了！");
            }

            //3、将数据添加到数据库[1次]
            Region region = regionMapper.selectById(srt.getRegionId());
            if(ObjectUtil.isEmpty(region)){
                throw new CommonException("区域非法！");
            }

            Serve serve = BeanUtil.toBean(srt, Serve.class);
            serve.setCityCode(region.getCityCode());
            int bo = baseMapper.insert(serve);
            if(bo==0){
                throw new CommonException("服务异常，添加失败！");
            }
        });
    }


    /**
     * 分页查询区域服务列表
     * @param servePageQueryReqDTO
     * @return
     */
    @Override
    public PageResult<ServeResDTO> page(ServePageQueryReqDTO servePageQueryReqDTO) {
        //2、使用PageHelper执行分页查询
        return PageHelperUtils.selectPage(servePageQueryReqDTO,
                //1、在Dao中定义方法查询指定区域的数据【集合查询，不需要关心分页】
                () -> baseMapper.queryServeListByRegionId(servePageQueryReqDTO.getRegionId()));
    }




}
